package net.chasing.retrofit.util;

import androidx.annotation.NonNull;

import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import net.chasing.retrofit.bean.base.ResponseResult;
import net.chasing.retrofit.util.encode.AESUtils;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 数据接收处理类
 * 在convert接收数据时进行解密
 */
public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, ResponseResult<T>> {

    private final TypeAdapter<ResponseResult<T>> adapter;

    public JsonResponseBodyConverter(TypeAdapter<ResponseResult<T>> adapter) {
        this.adapter = adapter;
    }

    @Override
    public ResponseResult<T> convert(@NonNull ResponseBody responseBody) {
        ResponseResult<T> t = null;
        String jsonString;
        try {
            jsonString = responseBody.string();

            // 整个内容加密的情况：
//            String decryptString = RetrofitConstant.decryptAES(jsonString);
            // 解密失败则用原字符串进行解析获取对象
//            if (TextUtils.isEmpty(decryptString)) {
//                t = adapter.fromJson(jsonString);
//                RetrofitLog.i("retrofit request response" + jsonString);
//            } else {
//                t = adapter.fromJson(decryptString);
//                RetrofitLog.i("retrofit request response" + decryptString);
//            }

            // 只对data加密的情况，则使用以下方式：
            // 先解析成ResponseResult<String>，之后对data解密重新赋值，然后转JsonString，再解析成ResponseResult<T>
            ResponseResult<Object> result = JsonUtils.fromJson(jsonString, new TypeToken<ResponseResult<Object>>() {
            }.getType());
            if (result != null) {
                if (result.getEncry() == 1) {
                    // 有加密
                    result.setData(AESUtils.decryptAES(JsonUtils.toJson(result.getData())));
                    jsonString = JsonUtils.toJson(result);
                    if (jsonString != null)
                        t = adapter.fromJson(jsonString);
                } else {
                    // 没加密
                    t = adapter.fromJson(jsonString);
                }
            }
        } catch (Exception e) {
            RetrofitLog.e("retrofit request convert error:" + e.getMessage());
        } finally {
            responseBody.close();
        }
        // 如果对象解析失败，则视为数据错误
        if (t == null) {
            t = new ResponseResult<>();
            t.setCode(-1);
            t.setMsg("数据异常");
        }
        return t;
    }
}
